import 'package:get/get.dart';
import 'package:tencent_cloud_chat_sdk/enum/V2TimConversationListener.dart';
import 'package:tencent_cloud_chat_sdk/models/v2_tim_conversation.dart';
import 'package:tencent_cloud_chat_sdk/tencent_im_sdk_plugin.dart';
import 'package:tencent_cloud_chat_uikit/ui/controller/tim_uikit_conversation_controller.dart';
import 'package:yqmssa_app/views/index/request/message_request.dart';

class MessageManager extends GetxController {
  @override
  void onInit() {
    super.onInit();
    getSystemMsg();
    messageAddListen();
  }

  final massageData = <MessageDM>[].obs;

  final itemData = MessageDM().obs;

  final controller = TIMUIKitConversationController();

  final message = V2TimConversation(conversationID: "").obs;

  final conversationManager = TencentImSDKPlugin.v2TIMManager.getConversationManager();

  final unRead = 0.obs;

  final msgUnread = 0.obs;

  late final conversationListen = V2TimConversationListener(onConversationChanged: (conversationList) {
    message.value = conversationList.first;
  }, onTotalUnreadMessageCountChanged: (readNum) {
    unRead.value = readNum;
  });

  void getSystemMsg() {
    MessageRequest.systemMsgList().then((value) {
      massageData.clear();
      massageData.addAll(value);
      msgUnread.value = massageData.map((a) => a.isRead).length;
      if (value.isNotEmpty) itemData.value = value.last;
      Future.delayed(const Duration(seconds: 5), getChatList);
    });
  }

  void getChatList() async {
    //获取会话列表
    final getConversationListRes = await conversationManager.getConversationList(count: 100, nextSeq: "0");
    if (getConversationListRes.code == 0) {
      message.value = (getConversationListRes.data?.conversationList ?? []).isEmpty
          ? V2TimConversation(conversationID: "")
          : getConversationListRes.data!.conversationList!.first;
    }
  }

  messageAddListen() {
    conversationManager.addConversationListener(
      listener: conversationListen,
    );
  }

  cleanUnRead() {
    msgUnread.value = 0;
    if (unRead.value > 0) {
      conversationManager.cleanConversationUnreadMessageCount(
          conversationID: message.value.conversationID, cleanTimestamp: DateTime.now().millisecondsSinceEpoch, cleanSequence: 1);
      unRead.value = 0;
    }
  }

  @override
  void dispose() {
    message.value = V2TimConversation(conversationID: "");
    conversationManager.removeConversationListener(
      listener: conversationListen,
    );
    super.dispose();
  }
}
